﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IceStart.View;
using System.IO;
using System.Windows.Controls;
using System.Windows;

namespace IceStart.Core
{
    /// <summary>
    /// 整个软件各种行为的控制
    /// </summary>
    public class DataHandler
    {
        public class MagnetInfo
        {
            public string Name { get; set; }
            public double Top { get; set; }
            public double Left { get; set; }
            public string Path { get; set; }
            public AbstractMagnetTie.Size Size { get; set; }
        }

        public static void SaveMagnet()
        {
            List<MagnetInfo> list = new List<MagnetInfo>();
            foreach (IMagnet m in Coordinates.MagnetTable.Keys)
            {
                if (m is FileMagnet fm)
                {
                    MagnetInfo info = new MagnetInfo()
                    {
                        Name = fm.FileName.Text,
                        Top = fm.nowTop,
                        Left = fm.nowLeft,
                        Path = fm.MagnetTie.FilePath,
                        Size = fm.MagnetTie.ButtonSize
                    };
                    list.Add(info);
                }
            }
            string json = JsonConvert.SerializeObject(list);
            StreamWriter writer = new StreamWriter(@"d:\IceStart.json");
            writer.WriteLine(json);
            writer.Flush();
            writer.Close();
        }

        public static void LoadMagnet()
        {
            string json = File.ReadAllText(@"d:\IceStart.json");
            List<MagnetInfo>? list = JsonConvert.DeserializeObject<List<MagnetInfo>>(json);
            if (list == null)
            {
                Environment.Exit(-1);
            }
            foreach (var m in list)
            {
                ((MainWindow)Application.Current.MainWindow).AddFileMagnet(m);
            }
        }
    }
}